<!--
@description ：选择客户弹窗
-->

<template>
    <el-row class="row-radar">
      <el-col :span="12">
        <el-form :model="queryForm" style="display: flex">
          <el-form-item prop="weUserId">
            <el-select v-model="queryForm.weUserId" placeholder="请选择超级企微" style="width: 140px;"
                       @change="handleQuery" clearable filterable>
              <el-option
                v-for="item in supermicroList"
                :key="item.weUserId"
                :label="item.userName"
                :value="item.weUserId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="name">
            <el-input
              v-model="queryForm.name"
              placeholder="搜索昵称/姓名" style="width: 200px"
              @blur="handleQuery">
              <i slot="suffix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
        </el-form>
        <el-table ref="multipleTable" v-loading="loading" :data="tableList" height="442px"
                  style="width: 100%" @select="handleSelectionChange" @select-all="handleSelected">
          <el-table-column type="selection" width="55"/>
          <el-table-column align="left" label="姓名" min-width="120px" prop="userName"
                           show-overflow-tooltip>
            <template slot-scope="{ row }">
              <div style="display: flex;align-items: center;justify-content: center">
                <img v-if="row.avatar" :src="row.avatar" alt=""
                     style="width:30px; height:30px;border-radius:50%;margin-right:6px">
                <span style="line-height: 30px">{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :offset="1" :span="11" style="border-left: 1px solid #eee; padding: 0px 15px 20px 15px;">
        <div style="color: #999999;line-height: 60px;margin-left: 26px;font-size: 18px">
          已选{{ checkedList.length || 0 }}个客户(最多可添加1000个客户)
        </div>
        <div v-if="checkedList.length > 0" class="selectedListArea">
          <div v-for="(item,index) in checkedList" :key="item.weUserId">
            <div v-if="item.weFriendList.length > 0" class="selectedListArea-list-item">
              <div class="selectedListArea-list-item-supermicroName">
                <span class="name">{{ item.userName }}</span>
                <span class="line"></span>
              </div>
              <div v-for="(itm, ind) in item.weFriendList" :key="itm.externalUserid" class="customer-item">
                <img alt="" :src="itm.avatar" v-if="itm.avatar">
                <img alt="" :src="defaultHeadImage" v-else>
                <span>{{ itm.name }}</span>
                <i class="el-icon-close" @click="delItem(index,ind, itm.externalUserid)"></i>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="noSelectedListArea">
          <img src="../assets/image/noGroup.png">
        </div>
      </el-col>
    </el-row>
</template>
<script>
import * as $api from '@/api/riskManager/blackList'
export default {
  name: "selectCustomer", //页面名称，必填
  props: {
    supermicroList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  computed: {
  },
  components: {},
  data() {
    return {
      checkedList: [], // 选中的数据
      queryForm: {
        weUserId: '',
        name: '',
        pageNum: 1,
        pageSize: 9999,
      },
      loading: false,
      tableList: [],
      defaultHeadImage: 'https://test-ztdata-1308072185.cos.ap-shanghai-fsi.myqcloud.com/siyu/2024/04/15/202404151353039078.png?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDAalfJgmb9QRBdoiMjpeEYcPwCAsJSKvF%26q-sign-time%3D1713160384%3B4866760384%26q-key-time%3D1713160384%3B4866760384%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3Db660d3547810e985073de32d0e0afeb8b784c657',
    }
  },
  watch: {},
  methods: {
    handleQuery(val) {
      console.log('val:::::::',val)
       let obj = {
         ...this.queryForm
       }
       this.loading = true
       this.tableList = []
       $api.selectFriend(obj).then(res => {
         if(res.code == 200){
           this.tableList = res.data
           this.$nextTick(() => {
             if (this.checkedList.some(item => item.weUserId == this.queryForm.weUserId && item.weFriendList && item.weFriendList.length > 0)) {
               const arr = this.checkedList.filter(item => item.weUserId == this.queryForm.weUserId)[0].weFriendList
               arr.forEach(item => {
                 this.tableList.forEach(element => {
                   if (element.externalUserid == item.externalUserid) {
                     this.$refs.multipleTable.toggleRowSelection(element);
                   }
                 })
               })
             }
           })
         }
         this.loading = false
       }).catch(() => {
         this.loading = false
       })
    },
    handleSelected(val){
      const userMap = new Map(this.supermicroList.map(item => [item.weUserId, item.userName]));
      const existingItem = this.checkedList.find(item => item.weUserId === this.queryForm.weUserId);
      console.log('existingItem::::::::', existingItem)
      if (existingItem) {
        // 如果存在，更新 userName 和 weFriendList
        this.checkedList = this.checkedList.map(item => {
          if(item.weUserId == this.queryForm.weUserId){
            return {
              ...item,
              weFriendList: val
            }
          }else{
            return {
              ...item
            }
          }
        })
      } else {
        // 如果不存在，创建新对象并 push 到 this.checkedList
        this.checkedList.push({
          weUserId: this.queryForm.weUserId,
          userName: userMap.get(this.queryForm.weUserId),
          weFriendList: val
        });
      }
      this.$emit('customerUpdate', this.checkedList)
    },
    handleSelectionChange(selection, val) {
      const userMap = new Map(this.supermicroList.map(item => [item.weUserId, item.userName]));
      // 检查 this.checkedList 中是否已经存在相应的 weUserId
      const existingItem = this.checkedList.find(item => item.weUserId === this.queryForm.weUserId);
      console.log(existingItem, 'existingItem::::::')
      if (existingItem) {
        this.checkedList = this.checkedList.map(item => {
          console.log('应该只比较了一次吧::::', item.weUserId == this.queryForm.weUserId)
          if(item.weUserId == this.queryForm.weUserId){
            return {
              ...item,
              weFriendList: selection || []
            }
          }else{
            console.log('这里为什么会有值', item)
            return {
              ...item
            }
          }
        })
      } else {
        // 如果不存在，创建新对象并 push 到 this.checkedList
        this.checkedList.push({
          weUserId: this.queryForm.weUserId,
          userName: userMap.get(this.queryForm.weUserId),
          weFriendList: selection
        });
      }
      this.$emit('customerUpdate', this.checkedList)
    },
    delItem(index,ind, val) {
      this.checkedList[index].weFriendList.splice(ind, 1)
      if(this.checkedList[index].weFriendList.length == 0) this.checkedList.splice(index, 1)
      this.tableList.forEach(element => {
        if(element.externalUserid == val)
        this.$refs.multipleTable.toggleRowSelection(element, false);
      })
      this.$emit('customerUpdate', this.checkedList)
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    ok() {
      this.$emit('update:visible', false)
    },
    clearSelected(){
      this.checkedList = []
      this.$refs.multipleTable.clearSelection();
      this.$emit('customerUpdate', this.checkedList)
    }
  },
  mounted() {
    this.queryForm.weUserId = this.supermicroList[0].weUserId
    this.handleQuery()
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>

.selectedListArea {
  margin-left: 26px;
  height: 440px;
  overflow-y: auto;
  background-color: #F6F6F6;
  padding-top: 12px;
  border-radius: 4px;
}

.noSelectedListArea {
  margin-left: 26px;
  width: 440px;
  height: 440px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #F6F6F6;
  border-radius: 4px;
}

.selectedListArea-list-item-supermicroName {
  line-height: 40px;
  display: flex;
  align-items: center;
  position: relative;
  padding-right: 12px;

  .name {
    width: auto;
    padding: 0 14px 0 20px;
    font-size: 18px;
    color: #505050;
    font-weight: 500;
  }

  .line {
    flex: 1;
    border: 1px solid #F0F0F0;
  }
}

.selectedListArea-list-item-close {
  position: absolute;
  right: 0;
  font-size: 22px;

  &:hover {
    color: #082AFF;
    cursor: pointer;
  }
}

.customer-item {
  padding: 6px 12px 6px 12px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  line-height: 42px;
  margin: 0 12px 8px 12px;
  border: 1px solid #EEEEEE;
  img{
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 8px;
  }
  span{
    flex: 1;
  }
  i{
    font-size: 20px;
    &:hover{
      color: #082AFF;
      cursor: pointer;
    }
  }
}

</style>
